package com.crm.crm.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.crm.annotation.Log;
import com.crm.crm.domain.*;
import com.crm.crm.domain.dto.AssignmentDto;
import com.crm.crm.domain.dto.CourseLIstDto;
import com.crm.crm.domain.dto.business.BusinessListDto;
import com.crm.crm.domain.dto.business.FalseCluesReportDto;
import com.crm.crm.domain.vo.CourseVo;
import com.crm.crm.domain.vo.business.BusinessVo;
import com.crm.crm.domain.vo.business.result.Result;
import com.crm.crm.domain.dto.business.RecordDto;
import com.crm.crm.domain.dto.PageQueryParams;
import com.crm.crm.domain.vo.ClueVo;
import com.crm.crm.domain.vo.PageResult;
import com.crm.crm.service.ClueService;
import com.crm.crm.service.CourseService;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

import static com.crm.crm.util.ExcelReader.getWorkbook;
import static com.crm.crm.util.ExcelReader.parseExcel;

@RestController
@RequestMapping("/clues")
public class ClueController {
    private static final Logger log = LoggerFactory.getLogger(ClueController.class);
    @Autowired
    private ClueService clueService;
    @Autowired
    private CourseService courseService;
    //新增

    @Log("新增线索")
    @PostMapping("/clue")
    public Result add(@RequestBody Clue clue) {
        String add = clueService.add(clue);
        if (add != null) {
            return Result.error(add);
        }
        return Result.success();
    }

    /**
     * 条件分页查询
     */
    @Log("分页查询线索")
    @GetMapping("/clue/list")
    public Result page(PageQueryParams pageQueryParams, @RequestParam Map<String, String> params) {
        log.info("分页查询参数：{}", pageQueryParams);
        pageQueryParams.setBeginCreateTime(params.get("params[beginCreateTime]"));
        pageQueryParams.setEndCreateTime(params.get("params[endCreateTime]"));
        PageResult<Clue> pageResult = clueService.pageQuery(pageQueryParams);
        return Result.success().put("total", pageResult.getTotal())
                .put("rows", pageResult.getRows());
    }

    /*查看相信信息*/
    @Log("查看线索信息")
    @GetMapping("/clue/{id}")
    public Result getById(@PathVariable Integer id) {
        ClueVo clueVo = clueService.getById(id);
        return Result.success(clueVo);
    }

    /*跟进回显*/
    @Log("跟进回显")
    @GetMapping("/record/list")
    public Result getRecordList(@RequestParam String clueId) {
        Integer id = Integer.parseInt(clueId);
        PageResult<RecordOne> result = clueService.getRecordList(id);
        return Result.success().put("total", result.getTotal()).put("rows", result.getRows());
    }

    /*新增跟进*/
    @Log("新增跟进")
    @PostMapping("/record")
    public Result addRecord(@RequestBody RecordDto recordDto) {
        clueService.addRecord(recordDto);
        return Result.success();
    }

    /*伪线索上报*/
    @Log("伪线索上报")
    @PutMapping("/clue/false/{id}")
    public Result falseClue(@RequestBody FalseCluesReportDto falseCluesReportDto, @PathVariable Integer id) {
        falseCluesReportDto.setId(id);
        clueService.falseClue(falseCluesReportDto);
        return Result.success();
    }

//批量插入

    /**
     * 读取Excel文件内容
     *
     * @param file 上传的Excel文件
     * @return 读取结果列表，读取失败时返回null
     */
    @Log("批量导入")
    @PostMapping("/clue/importData")
    public Result readExcel(@RequestParam MultipartFile file) {

        Workbook workbook = null;

        try {
            // 获取Excel后缀名
            String fileName = file.getOriginalFilename();
            if (fileName == null || fileName.isEmpty() || fileName.lastIndexOf(".") < 0) {
                log.info("解析Excel失败，因为获取到的Excel文件名非法！");
                return null;
            }
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());

            // 获取Excel工作簿
            workbook = getWorkbook(file.getInputStream(), fileType);

            // 读取excel中的数据
            List<Clue> resultDataList = parseExcel(workbook);
            clueService.saveClues(resultDataList);
            return Result.success();
        } catch (Exception e) {
            log.info("解析Excel失败，文件名：" + file.getOriginalFilename() + " 错误信息：" + e.getMessage());
            return null;
        } finally {
            try {
                if (null != workbook) {
                    workbook.close();
                }
            } catch (Exception e) {
                log.info("关闭数据流出错！错误信息：" + e.getMessage());
                return null;
            }
        }
    }

    //分配和批量分配
    @Log("分配")
    @PutMapping("/clue/assignment")
    public Result assignment(@RequestBody AssignmentDto assignmentDto) {
        String assignment = clueService.assignment(assignmentDto);
        if (assignment != null) {
            return Result.error(assignment);
        }
        return Result.success();
    }

    //分页查询池pool
    @Log("分页查询池pool")
    @GetMapping("/clue/pool")
    public Result pool(PageQueryParams pageQueryParams, @RequestParam Map<String, String> params) {
        log.info("分页查询参数：{}", pageQueryParams);
        pageQueryParams.setBeginCreateTime(params.get("params[beginCreateTime]"));
        pageQueryParams.setEndCreateTime(params.get("params[endCreateTime]"));
        PageResult<CluePool> pageResult = clueService.poolQuery(pageQueryParams);
        return Result.success().put("total", pageResult.getTotal())
                .put("rows", pageResult.getRows());
    }

    //捞取
    @Log("捞取")
    @PutMapping("/clue/gain")
    public Result gain(@RequestBody AssignmentDto gain) {
        String result = clueService.gain(gain);
        if (result != null) {
            return Result.error(result);
        }
        return Result.success();
    }

    @Log("线索转商机")
    @PutMapping("/clue/changeBusiness/{id}")
    public Result changeBusiness(@PathVariable Integer id) {
        clueService.changeBusiness(id);
        return Result.success();
    }

//    =========================
//    课程的接口写在这下面的
//    =========================

    //新增课程
    @Log("新增课程")
    @PostMapping("/course")
    public Result addCourse(@RequestBody Course course) {
        Integer count = courseService.add(course);
        return count > 0 ? Result.success() : Result.error();
    }


    //课程分页查询
    @GetMapping("/course/list")
    public Result list(CourseLIstDto dto,
                       @RequestParam Map<String, String> params) {
        dto.setBeginCreateTime(params.get("params[beginCreateTime]"));
        dto.setEndCreateTime(params.get("params[endCreateTime]"));
        log.info("分页查询参数：{}", dto);
        // 创建分页对象（pageNum 是当前页码，pageSize 是每页记录数）
        Page<Course> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        // 调用 service 分页查询方法
        Page<Course> resultPage = courseService.list(dto, page);
        log.info("分页查询结果：{}", resultPage);
        // 将 Page<Course> 转换为 List<CourseVo>
        List<CourseVo> voList = resultPage.getRecords().stream()
                .map(course -> {
                    CourseVo vo = new CourseVo();
                    BeanUtils.copyProperties(course, vo);
                    vo.setId(course.getID());
                    vo.setCode(String.valueOf(course.getID()));
                    return vo;
                })
                .toList();
// 构造最终结果：将 total 和 rows 提升到顶层
        Result result = Result.success();
        result.put("total", resultPage.getTotal());
        result.put("rows", voList);
        return result;
    }

    //    删除课程，包含批量删除
    @Log("删除课程")
    @DeleteMapping("/course/{ids}")
    public Result delete(@PathVariable String[] ids) {
        log.info("删除课程参数：{}", ids);
        Integer count = courseService.deleteByIds(ids);
        return count > 0 ? Result.success() : Result.error();
    }

    //根据id查询课程
    @GetMapping("/course/{id}")
    public Result updateById(@PathVariable Integer id) {
        Course course = courseService.getById(id);
        return Result.success(course);
    }

    //修改课程
    @Log("修改课程")
    @PutMapping("/course")
    public Result update(@RequestBody Course course) {
        log.info("修改课程参数：{}", course);
        Integer count = courseService.updateById(course);
        return count > 0 ? Result.success() : Result.error();
    }

    //    根据学科查询有这个学科的课程
    @GetMapping("/course/listselect")
    public Result listSelect(@RequestParam(required = false) Integer subject) {
        log.info("根据学科ID查询有这个学科的课程参数：{}", subject);
        List<Course> list = courseService.listSelect(subject);
        log.info("根据学科ID查询有这个学科的课程结果：{}", list);
        return Result.success(list);
    }


}
